<?
/*

	Various blog functions
	
*/


/* Fetch list of supported services */
function fetchServices() {
		global $blogRoot,$pluginServices;
		
		$configFile = $blogRoot."settings/services.txt";
		// file exists?
		if(file_exists($configFile)) {
			if(!(is_writable($configFile))) {
				print "<strong>the settings file \"".$configFile."\" is not writeable</strong>";
			}
		} else {
			// create the file :)
			$create = touch($configFile);
			chmod($configFile,0777);
			if(!($create)) {
				print "<strong>the settings file \"".$configFile."\" could not be made</strong>";
			}
		}


		// read contents
		clearstatcache();
		$open3 = fopen($configFile, "rb");
			if(filesize($configFile)!="0") $contents = fread($open3, filesize($configFile));
		fclose($open3);
		
		// display services
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		$serviceContent="";
		
		foreach ($entrylist as $item) {
			if (trim($item)!="") {
				$entry=explode("|",$item);
				
				print "<span id='serviceIcon".$entry[0]."'><a href='#' onClick='swap(\"service".$entry[0]."\"); return false;'><img src='".serviceIcon($entry[1])."' title='".$entry[1]." - ".$entry[2]."'></a></span> ";

			
				$serviceContent.="<div id='service".$entry[0]."' style='display:none; border:1px solid #dedede; background: #efefef; padding:1; margin: 0 0 5 0;'>";
				$serviceicon=serviceIcon($entry[1]);
				if ($serviceicon) $serviceContent.="<img src='".$serviceicon."' > ";
				
				if (function_exists($entry[1]."_identify")) $serviceContent.=call_user_func($entry[1]."_identify",$item);
				else  $serviceContent.=" from <a href='".$entry[3]."'>".$entry[2]."</a>";
				
				$serviceContent.="<br/><span style='padding-left:25px;'>";
				
				$serviceContent.="<a href='#' onClick='updService(\"".$entry[0]."\"); return false;'>refresh</a>";
				$serviceContent.=" | <a href='#' onClick='delService(\"".$entry[0]."\"); return false;'>delete</a>";
				
				$serviceContent.="</span>";		
				$serviceContent.="</div";
			}
		}
		
		print "<br/>";
		print $serviceContent;
		
}




/* Add a service */
function addService() {
	$serviceID=$_POST['addservice'];
	$username=$_POST['username'];
	$found=false;
	
	if (function_exists($_POST['addservice']."_addProfile")) {
		call_user_func($_POST['addservice']."_addProfile","");
	}
}


function writeService($serviceID,$username,$rsslink) {
		// write the new feed to the settings and import !
		$configFile = $blogRoot."settings/services.txt";
		
		// read contents
		clearstatcache();
		$open1 = fopen($configFile, "rb");
			if(filesize($configFile)!="0") $contents = fread($open1, filesize($configFile));
		fclose($open1);


		$open1 = fopen($configFile, "w");

		// fetch all current entries
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		$duplicate=false;
		// process the list, and insert into our new array (unless the guid is duplicate!)
		$first=true;
		$highestService=0;
		foreach ($entrylist as $item) {
			$entry=explode("|",$item);
			if (trim($item)!="") {
				if ($entry[0]>$highestService) $highestService=$entry[0];
				
				if ($entry[3]==$rsslink) $duplicate=true;
				if (!$first) fwrite($open1,"\r\n");
				fwrite($open1,$item);
				$first=false;
			}
		}
		
		// not duplicate? then we write the new service 
		if (!$duplicate) {
			$highestService++;
			if (!$first) fwrite($open1,"\r\n");
			fwrite($open1,$highestService."|".$serviceID."|".$username."|".$rsslink);
		}
		
		fclose($open1);
}





/*

	Side bar adminning
	
*/	


/* Fetch list of supported services */
function fetchSidebarPlugins() {
		global $blogRoot;
		
		$configFile = $blogRoot."settings/sidebar.txt";
		// file exists?
		if(file_exists($configFile)) {
			if(!(is_writable($configFile))) {
				print "<strong>the settings file \"".$configFile."\" is not writeable</strong>";
				return;
			}
		} else {
			// create the file :)
			$create = touch($configFile);
			chmod($configFile,0777);
			if(!($create)) {
				print "<strong>the settings file \"".$configFile."\" could not be made</strong>";
				return;
			}
		}


		// read contents
		clearstatcache();
		$open3 = fopen($configFile, "rb");
			if(filesize($configFile)!="0") $contents = fread($open3, filesize($configFile));
		fclose($open3);
		
		// display services
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		$pluginCount=0;
		print "<ul id='arrangableNodes'>";
		
		foreach ($entrylist as $item) {
			if (trim($item)!="") {
				$pluginCount++;
				$entry=explode("|",$item);

				print "<li id='node".$pluginCount."'> ";
				
				print "<div id='service".$entry[0]."' style='border:1px solid #dedede; background: #efefef; padding:1; margin: 0 0 5 0; width:400px;'>";

				/*print "<span style='padding-left:25px; float:right;'>";
					if ($pluginCount>1) print "<a href='#' onClick='sortPlugin(\"".$entry[0]."\",\"-1\");' return false;'> Up</a><br/>";
					else print "<br/>";
					print "<a href='#' onClick='sortPlugin(\"".$entry[0]."\",\"-1\");' return false;'>Down</a><br/>";
				print "</span>";
				*/

				
				print "<strong>".$entry[2]."</strong> (<small>";
				
				if (function_exists($entry[1]."_pluginName")) print call_user_func($entry[1]."_pluginName");
				else  print "unknown plugin";
				
				print "</small>)  <small style='float:right;'>";

				if (call_user_func($entry[1]."_hasEdit")==true) {
					print "<a href='#' onClick='updPlugin(\"".$entry[0]."\"); return false;'>edit</a> | ";
				}
				print "<a href='#' onClick='delPlugin(\"".$entry[0]."\"); return false;'>delete</a>";
				print "</small>";
				
				print "</div>";
				print "</li>";
			}
		}
		
		print "</ul>";

		print "<div id='movableNode'><ul></ul></div>	";
		print "<div id='arrDestInditcator'><img src='".$blogRoot."themes/_system/imgs/insert.gif'></div>";
		print "<div id='arrDebug'></div>		";
		print "<br/>";
		print "<a href='#' onclick='sortPlugin();return false'>Save</a>";
		print "<form method='post' action='????'>";
		print "<input type='hidden' name='hiddenNodeIds'>";
		print "</form>";
		
}





/* Add a plugin */
function addPlugin($serviceType,$isupdate=false) {
	
	if (!$isupdate) {
		$serviceID=$_POST['addPlugin'];
		if (function_exists($_POST['addPlugin']."_addPlugin")) {
			$serviceentry=call_user_func($_POST['addPlugin']."_addPlugin","");
			if ($_POST["title"]) $serviceTitle=$_POST["title"];
			else $serviceTitle="";
		} else {
			print "Plugin is not compatible with this version of Puddle.";
			return;
		}
	} else {
		$serviceID=$_POST["updPlugin"];
		$serviceentry=call_user_func($_POST['updType']."_addPlugin","");
		
		if ($_POST["title"]) $serviceTitle=$_POST["title"];
		else $serviceTitle="";
	}
	
	
	writePlugin($serviceID,$serviceType,$serviceentry,$isupdate,$serviceTitle);
}


function writePlugin($serviceID,$servicetype,$serviceentry,$isupdate,$servicetitle) {

		// write the new feed to the settings and import !
		$configFile = $blogRoot."settings/".$servicetype.".txt";

		// change all returns into <br/>'s
		$serviceentry=str_replace(CHR(13),'',$serviceentry);
		$serviceentry=str_replace(CHR(10),'',$serviceentry);
		$serviceentry=str_replace('|',':',$serviceentry);


		
		// read contents
		clearstatcache();
		$open1 = fopen($configFile, "rb");
			if(filesize($configFile)!="0") $contents = fread($open1, filesize($configFile));
		fclose($open1);


		$open1 = fopen($configFile, "w");

		// fetch all current entries
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		// process the list, and insert into our new array
		$first=true;
		$highestService=0;
		foreach ($entrylist as $item) {
			$entry=explode("|",$item);
			if (trim($item)!="") {
			
				if ($isupdate && $entry[0]==$serviceID) {
					$entry[3]=$serviceentry;
					$entry[2]=$servicetitle;
				} 
			
				if ($entry[0]>$highestService) $highestService=$entry[0];
				
				if (!$first) fwrite($open1,"\r\n");
				fwrite($open1,$entry[0]."|".$entry[1]."|".$entry[2]."|".$entry[3]);
				$first=false;
			}
		}
		
		// not duplicate? then we write the new service 
		if (!$isupdate) {
			$highestService++;
			if (!$first) fwrite($open1,"\r\n");
			fwrite($open1,$highestService."|".$serviceID."|".$servicetitle."|".$serviceentry);
		}

		fclose($open1);
}








function formatTweet($line) {
	global $blogRoot;
	
	$entry=explode("|",$line);

		// load date
		$date = substr($entry[0],0,10);

		$itemDate="";
		$explodeDate=explode(".",$date);
							
		// day
		if(substr($explodeDate[0],0,1)=="0") {
			$itemDate.=substr($explodeDate[0],1,2);
		} else {
			$itemDate.=$explodeDate[0];
		}
		
		// month
			$itemDate.=$lang["months"][str_replace("0","",$explodeDate[1])];
		// and year
			$itemDate.=' '.$explodeDate[2];
				$date = explode(".",$date);
				$time= substr($entry[0],11,8);
				// explode time for unixtime
				$time = explode(":",$time);
				// create unixtime
				$unixtime = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
				
				
				// check on timestamp time value, and beautify it
				$date=strtotime($entry[0]);
				$timeline="";
				if (date("Ymd",time())==date("Ymd",$date)) {
					// it's today, so make the time nicer
					if (date("H",time())==date("H",$date)) {
						$minAgo=date("i",time())-date("i",$date);
						$itemDate=$minAgo." minutes ago";
					} else {
						$itemDate="Today @ ".date("Y.m.d H:i",$date); //date("H:i",$entry[0]);
					}
				} else if (date("Ymd",time())==date("Ymd",$date)-1) {
					$itemDate="Yesterday @ ".date("H:i",$date);
				} else {
					$itemDate.=" @ ".date("H:i",$date);
				}
				
			$myService=$entry[2];
			
			if (function_exists($myService."_getAction")) $itemAction=call_user_func($myService."_getAction",$line);
			else $itemAction=null;
			$itemCaption=call_user_func($myService."_getCaption",$line);
			$itemPost=call_user_func($myService."_getPost",$line);
			$itemLink=call_user_func($myService."_getLink",$line);
			$itemCommentLink='<a href="?cmt='.$unixtime.'#disqus_thread">Comments (View)</a>';
			if ($loggedIn && $myService=='puddle') $itemCommentLink.=" | <a href='".$blogRoot."admin.php?page=puddle&edit=".$unixtime."'>Edit</a>";
			

			if (!strpos($entry[1],":h")) $text="<tr id='tweet".$unixtime."'>";
			else $text="<tr class='hidden' id='tweet".$unixtime."'>";
			
			$text.="<td>";
			
			if ($itemCaption) {
				if (strlen($itemCaption)>40) $text.=substr($itemCaption,0,40)."...";
				else $text.=$itemCaption;
			} else {
				$text.=$itemAction;
			}

			$text.="<br/><span style='padding-left:25px;'><a href='#' >Edit</a>";
			
			if (!strpos($entry[1],":h"))  {
				$divshow="";
				$divhide="display:none;";
			} else {
				$divshow="display:none;";
				$divhide="";
			}
			
			$text.="<span id='hide".$unixtime."' style='".$divshow."'>| <a href='#' onClick='hideTweet(\"$unixtime\"); return false;'>Hide</a></span>";
			$text.="<span id='show".$unixtime."' style='".$divhide."'>| <a href='#' onClick='showTweet(\"$unixtime\"); return false;'>Unhide</a></span>";
			
			$text.="</span>";
			
			$text.="</td>";
			
			$text.="<td>".$myService."</td>";
			$text.="<td>".$itemDate."</td>";
			$text.="</tr>";
			$returnComment.=$text;
					
		return $returnComment;


	
}

/**
	Load all posts, or specific posts, and show them in a list for editing/maintaining
*/
function loadPosts($page,$hidden) {
		global $blogRoot,$lang,$pluginServices, $tweetfile,$lang;
		$returnComment="";
		$text="";
		

		clearstatcache();
		
		$pagey=date("Y",time());
		$pagem=date("m",time());
		
		$pageCount=1;
		$postCount=0;
		
			
		$myfile=$blogRoot."txts/".$pagey.".".$pagem.".txt";
		
		$fileNotFound=0;
		


		while ($postCount<25) {
			
			// file exists and have zero size?
			if((file_exists($myfile)) && filesize($myfile)!="0") {
				// load archive
				$load = @file($myfile);
		
				// load lines
				while(count($load)>0 && $postCount<25) {
					$line=array_shift($load);
					$items=explode("|",$line);


					if ($pageCount==$page) {
						$include=true;
						
						/*
						if ($hidden) {
							if (!strpos($items[1],":h")) $include=false;
						} else {
							if (strpos($items[1],":h")) $include=false;
						}
						*/
							
						
						if ($include) $returnComment.=formatTweet($line);
						else $postCount--;
					}
					$postCount++;

					if ($postCount==25) {
						if ($pageCount<$page) {
							$postCount=0;
							$pageCount++;
						}
					}
				}

			} else {
				$fileNotFound++;
				if ($fileNotFound>5) break;
			}
			
			$pagem--;
			if ($pagem<1) {
				$pagem=12;
				$pagey--;
			}
			if (strlen($pagem)<2) $pagem="0".$pagem;
			$myfile=$blogRoot."txts/".$pagey.".".$pagem.".txt";
		}


		// previous page? with newer items
		if ($page>1) {
			$returnComment.="<a href='?page=posts&idx=".($page-1)."'>Newer</a>";
		}
		
		// older pages? with older items
		if (count($load)>0 || ((file_exists($myfile)) && filesize($myfile)!="0") ) {
			$returnComment.=" <a href='?page=posts&idx=".($page+1)."'>Older</a>";
		}
		
		


		return $returnComment;
}


?>